# -*- coding: utf-8 -*-
"""生成index.rst"""
import os
import pathlib

CURRENT_DIR = pathlib.Path(__file__).parent

index_filename = 'index.rst'


top_dirs = {
    'software': '软件资料',
    'tool': '工具资料'
}


template = """{title}
{symbol}

.. toctree::
   :maxdepth: 2

{doc_tree}
"""


def write_file(filepath, content):
    if os.path.isfile(filepath):
        os.remove(filepath)
    with open(filepath, 'w', encoding='utf-8') as fw:
        fw.write(content)


def main():
    for language in ('en', 'zh-CN'):
        language_dir = CURRENT_DIR.joinpath(language)
        if not language_dir.is_dir():
            continue
        top_index_rst = language_dir.joinpath(index_filename)
        title = 'WS63指导资料'
        symbol = len(title) * 2 * '='

        exist_dir = []
        for doc_dir, sub_title in top_dirs.items():
            doc_dir_path = language_dir.joinpath(doc_dir)
            if not doc_dir_path.is_dir():
                continue
            exist_dir.append(doc_dir)
            sub_index_rst = doc_dir_path.joinpath(index_filename)
            sub_symbol = len(sub_title) * 3 * '='
            sub_dirs = []
            sub_md_files = []
            for sub_path in doc_dir_path.iterdir():
                if sub_path.is_dir():
                    sub_dirs.append(f'   {sub_path.name}/index\n')
                    sub2_index_rst = sub_path.joinpath(index_filename)
                    sub2_titles = [f'   {md.name.strip(".md")}\n' for md in sub_path.glob('*.md')]
                    sub2_symbol = len(max(sub2_titles, key=len)) * 3 * '='
                    sub2_doc_tree = ''.join(sub2_titles)
                    sub2_index_content = template.format(title=sub_path.name,
                                                         symbol=sub2_symbol,
                                                         doc_tree=sub2_doc_tree)
                    write_file(sub2_index_rst, sub2_index_content)
                else:
                    if sub_path.name.endswith('.md'):
                        sub_md_files.append(f'   {sub_path.name.strip(".md")}\n')
            sub_dirs.sort()
            sub_index_lines = sub_dirs + sub_md_files
            sub_doc_tree = ''.join(sub_index_lines)
            sub_index_content = template.format(title=sub_title, symbol=sub_symbol, doc_tree=sub_doc_tree)
            write_file(sub_index_rst, sub_index_content)
        lines = [f'   {key}/index\n' for key in exist_dir]
        doc_tree = ''.join(lines)
        top_index_content = template.format(
            title=title, symbol=symbol, doc_tree=doc_tree
        )
        write_file(top_index_rst, top_index_content)


if __name__ == '__main__':
    main()